<template>
  <div class="panel_h">
    <el-form
      :model="form"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
      label-position="top"
    >
      <el-form-item label="活动类型：" prop="module_type">
        <el-select v-model="form.module_type" placeholder="请选择活动类型" @change="changeModule">
          <el-option
            v-for="(item, index) in classList"
            :key="index"
            :label="item"
            :value="index"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="积分：" v-if="form.module_type == 4 || form.module_type == 6" prop="score">
        <el-input v-model="form.score"
            placeholder="请输入积分"
            type="number"
            maxlength="10"
            clearable
            :rules="{ required: true, message: '积分不能为空', trigger: 'blur' }"
          ></el-input>
      </el-form-item>
      <div class="flex alignend">
        <el-form-item label="开奖设置" prop="type">
          <el-select v-model="form.type" :disabled='status >= 1' placeholder="请选择开奖设置" @change="changeType">
            <el-option
              v-for="(item, index) in statusList"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.type == 3" label=" " prop="open_draw.full_num" class="ml_30">
          <el-input
            v-model="form.open_draw.full_num"
            placeholder="请输入开奖人数"
            maxlength="10"
            clearable
            :rules="{ required: true, message: '开奖人数不能为空', trigger: 'blur' }"
          ></el-input>
        </el-form-item>
      </div>
      <el-form-item label="活动标题" prop="name">
        <el-input
          v-model="form.name"
          placeholder="请输入活动标题"
          maxlength="30"
          show-word-limit
          clearable
        ></el-input>
      </el-form-item>
      <el-row>
        <el-col :span="11">
          <el-form-item prop="draw_startime" label="抽奖开始时间">
            <el-date-picker
              type="datetime"
              placeholder="选择开始时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              v-model="form.draw_startime"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col class="line" :span="2"> </el-col>
        <el-col :span="11">
          <el-form-item prop="draw_endtime" label="抽奖结束时间">
            <el-date-picker
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择抽奖结束时间"
              v-model="form.draw_endtime"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="抽奖说明" prop="introduce">
        <Tinymce ref="tinymce" :msg="form.introduce" TinymceName='wxhome' @msgBasic="msgBasic" :height='320'></Tinymce>
      </el-form-item>
      <div class="c_000 f-14 mb_10"> <span style="color:#ff4949">*</span> 图文介绍 <span class="f-14 c_D00000 pl_10">抽奖活动必填，红包抽奖活动非必填</span></div>
      <div class="bg_F8F8F8 picbox mb_15">
        <el-form-item :prop="form.module_type==='2'?'':'introduce_photo'">
          <template slot="label">
            <span class="f-14">图片上传</span>
            <span class="f-14 c_D00000 pl_10">最多上传十张</span>
          </template>
          <ImageUpload ref="imageupload" v-model="form.introduce_photo" :limit='10' />
        </el-form-item>
        <el-form-item label="文字描述" prop="introduce_text">
          <Tinymce ref="tinymcetwo" :msg="form.introduce_text" TinymceName='wxhome' @msgBasic="msgBasictwo" :height='320'></Tinymce>
        </el-form-item>
      </div>
      <el-button type="primary" @click="save">保存</el-button>
    </el-form>
  </div>
</template>

<script>
import Tinymce from "@/components/Tinymce/index.vue";
// import TinymceTwo from "@/components/Tinymce/index.vue";

// import { taskInfo, taskDataEdit,taskDataSave } from '@/api/active'
import { getDefaultData,taskInfo, taskDataEdit, taskDataSave} from '@/api/sethome'
export default {
  data() {
    var validateEndTime = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请选择抽奖结束时间'));
      } else {
        var start = new Date(this.form.draw_startime).getTime()
        var end = new Date(value).getTime()
        if (end<=start) {
          // this.msgError(this.$t('结束时间必须大于开始时间'))
          callback(new Error('结束时间必须大于开始时间!'));
          // this.form.endDate = undefined
        }
        callback();
        // callback(new Error('两次输入密码不一致!'));
      }
    };

    var validateStartTime = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请选择抽奖开始时间'));
      } else {
        var start = new Date(value).getTime()
        var end = new Date(this.form.draw_endtime).getTime()
        if (start>=end) {
          // this.msgError(this.$t('结束时间必须大于开始时间'))
          callback(new Error('开始时间不能大于结束时间!'));
          // this.form.endDate = undefined
        }
        callback();
      }
    };

    return {
      classList:[],
      taskid:'',
      t_id:'',
      info:{},
      status:0,
      statusList: [
        { name: "即抽开奖", id: 1 },
        { name: "定时开奖", id: 2 },
        { name: "满人开奖", id: 3 },
      ],
      plantList:[],
      form: {
        id:'',
        template_id:'',
        module_type:'',
        score:'',
        // is_tp:0,
        // tp_name:undefined,
        // tp_id:undefined,
        type:'1',
        open_draw:{
          full_num:''
        },
        name:'',
        draw_startime:'',
        draw_endtime:'',
        notice:'',
        introduce:'',
        introduce_photo:[],
        introduce_text:''
      },
      rules: {
        name:[{ required: true, message: '请输入活动标题', trigger: 'blur' }],
        type:[{ required: true, message: '请选择开奖设置', trigger: 'change' }],
        module_type:[{ required: true, message: '请选择活动类型', trigger: 'change' }],
        draw_startime:[{ required: true, message: '请选择抽奖开始时间', trigger: 'change' },
          { validator: validateStartTime, trigger: 'change' }
        ],
        draw_endtime:[
          { required: true, message: '请选择抽奖结束时间', trigger: 'change' },
          { validator: validateEndTime, trigger: 'change' },
        ],
        introduce:[{ required: true, message: '请输入活动介绍', trigger: 'change' }],
        // introduce_photo:[{ required: true, message: '请上传图片', trigger: 'change' }],
        // tp_name:[{ required: true, message: '请选择投票平台', trigger: 'change' }],
        // tp_id:[{ required: true, message: '请选择投票活动id', trigger: 'blur' }],
      },
    };
  },
  props:{
    activeId:{
      default:''
    },
    ischange:{
      default:''
    }
  },
  components: {
    Tinymce
  },
  created(){
    let query = this.$route.query
    if(query.template_id){
      this.form.template_id = query.template_id
    }
    console.log('activeId:',this.activeId)
    this.taskid = this.activeId
    if(this.taskid){
      this.getInfo() //获取活动信息
    }else{
      this.getDefault() //获取默认参数
    }
    this.getDicts('/user/index_task/getModuleList').then(res=>{
      this.classList = res.data
    })
    this.getDicts('/user/task/tpList').then(res=>{
      this.plantList = res.data
    })
  },
  watch:{
    ischange: {
      immediate: false,
      handler: function (val){
        console.log('改变摸吧了--',val)
        this.form.template_id = val
        this.save()
      }
    },
    activeId:{
      immediate: false,
      handler: function (val){
        console.log('activeId有了--',val)
        this.taskid = val
        this.form.id = val
      }
    },
    'form.module_type':{
      immediate: true,
      handler: function (val){
        if(val !== '2'){
          this.addRule('introduce_photo',[{ required: true, message: '请上传图片', trigger: 'change' }])
        }else{
          this.addRule('introduce_photo',[])
        }
      }
    },
  },
  methods: {

    addRule(prop,rule){
      this.$set(this.rules, prop, rule)
    },

    getDefault(){
      getDefaultData().then(res=>{
        let data = res.data
        this.form.name = data.task.name
        this.form.introduce = data.task.introduce
        let day = Date.now()
        let today = this.parseTime(day)
        let seven = this.parseTime(day + 7 * 24 * 60 * 60 * 1000);
        this.form.draw_startime = today
        this.form.draw_endtime = seven
        this.form.introduce_photo = data.task.introduce_photo?data.task.introduce_photo:[]
        this.form.type = data.task.type
        this.form.module_type = data.task.module_type+''
        this.form.introduce_text = data.task.introduce_text
        if(data.task.open_draw){
          this.form.open_draw.full_num = data.task.open_draw.full_num
        }
        this.form.notice = data.task.notice
      })
    },

    changeTp(val){
      if(!val){
        this.form.tp_name = undefined
        this.form.tp_id = undefined
      }
    },

    changeModule(val){
      this.$refs['ruleForm'].clearValidate('introduce_photo')
    },

    changeType(type){
      if(type!==3){
        this.form.open_draw.full_num = ''
      }
      // this.onchangeTab(this.form)
      this.$emit('changeType',this.form.type)
    },

    getInfo(){
      taskInfo({task_id:this.taskid}).then(res=>{
        let data = res.data
        this.info = data
        this.t_id = data.task.t_id
        this.status = data.task.status
        this.form.id = data.task.id
        this.form.is_tp = data.task.is_tp
        this.form.template_id = data.task.template.id
        this.form.name = data.task.name
        this.form.notice = data.task.notice
        this.form.draw_startime = data.task.draw_startime
        this.form.draw_endtime = data.task.draw_endtime
        this.form.introduce = data.task.introduce
        this.form.type = data.task.type
        this.form.tp_name = data.task.tp_name
        this.form.tp_id = data.task.tp_id||''
        if(data.task.open_draw){
          this.form.open_draw.full_num = data.task.open_draw.full_num
        }
        this.form.module_type = data.task.module_type+''
        this.form.score = data.task.score
        this.form.introduce_text = data.task.introduce_text
        this.form.introduce_photo = data.task.introduce_photo?data.task.introduce_photo:[]
        this.$emit('getTemplate', this.form.template_id)
        this.$emit('getBgurl', data.task.template.url)

      })
    },

    // 测试
    msgBasic(parmas) {
      this.form.introduce = parmas
    },

    msgBasictwo(parmas){
      this.form.introduce_text = parmas
    },

    save(){
      console.log('val"', this.form)
      this.$refs.ruleForm.validate(valid=>{
        console.log('valid:', valid)
        if(!valid) return
        if(!this.form.id){
          this.$emit('saveAll')
          return
        }
        let params = {
          ...this.form,
          introduce_photo:Array.isArray(this.form.introduce_photo)?this.form.introduce_photo:this.form.introduce_photo.split(',')
        }
        // console.log('params:', params)
        //已发布
        if(this.status == 1){
          taskDataSave(params).then(()=>{
            this.$message.success('编辑成功')
            this.getInfo()
          })
        }else{
          //未发布
          taskDataEdit(params).then(()=>{
            this.$message.success('编辑成功')
            this.getInfo()
          })
        }
      })
    }

  },
};
</script>
<style lang="scss" scoped>
.panel_h {
  height: calc(100vh - 239px);
  overflow-y: auto;
  padding-right: 12px;

  &::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 4px; /*高宽分别对应横竖滚动条的尺寸*/
    height: 1px;
  }
  &::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 10px;
    box-shadow: inset 0 0 5px rgba(97, 184, 179, 0.1);
    background: #c1c1c1;
  }
  &::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    box-shadow: inset 0 0 5px rgba(87, 175, 187, 0.1);
    border-radius: 10px;
    background: #ededed;
  }
}
.line {
  height: 82px;
}
.el-form-item {
  margin-bottom: 16px;
}
::v-deep .el-switch__label {
  position: absolute;
  display: none;
  color: #fff;
}
/*打开时文字位置设置*/
::v-deep .el-switch__label--right {
  z-index: 1;
  right: 24px;
}
/*关闭时文字位置设置*/
::v-deep .el-switch__label--left {
  z-index: 1;
  left: 24px;
}
/*显示文字*/
::v-deep .el-switch__label.is-active {
  display: block;
}
::v-deep .el-switch .el-switch__core,
.el-switch .el-switch__label {
  width: 55px;
}
::v-deep label {
  font-weight: normal;
}
::v-deep .el-form-item__label {
  color: #000;
  font-size: 15px;
}
.picbox{
  padding: 10px 15px;
}
</style>